package ming.controller.socket;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/mwebsocket/{bindToken}") //此注解相当于设置访问URL
public class MachineWebSocket {

    private String machineId;
    protected Session session;

    private static ConcurrentHashMap<String,MachineWebSocket> webSocketMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "bindToken") String bindToken) {
        try {
            this.session = session;
            session.setMaxIdleTimeout(60000*3);//3分钟生命周期
            this.machineId = machineId.trim();
            if (webSocketMap.containsKey(this.machineId)){
                CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,this.machineId+"重连，关闭以前的连接！");
                webSocketMap.get(this.machineId).session.close(closeReason);
                webSocketMap.remove(this.machineId);
            }else{
                webSocketMap.put(this.machineId,this);
            }

        } catch (Exception e) {
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error){
    }


    @OnClose
    public void onClose() {
        try {
            webSocketMap.remove(this.machineId);
        } catch (Exception e) {
        }
    }

    public String getSessionToMachineId(Session session)throws Exception{
        Map<String,String> map = session.getPathParameters();
        String bindToken = map.get("bindToken");
        return bindToken;
    }

    int i = 0;
    /**
     * 接受消息  设备心跳缓存
     * @param message
     */
    @OnMessage
    public void onMessage(String message,Session session) {

    }


    private Session getMachineSession(String machineId){
        MachineWebSocket machineWebSocket = webSocketMap.get(machineId.trim());
        if (machineWebSocket == null){
            return null;
        }
        Session sessionCache = machineWebSocket.session;
        if (sessionCache!=null){
            if (!sessionCache.isOpen()){
                try {
                    sessionCache.close();
                } catch (IOException e) {
                }
            }
        }else{
        }
        return sessionCache;
    }

}
